<template>
  <view class="search-container">
    <!-- 顶部 -->
    <view class="search-box">
      <icon type="search" size="18"></icon>
      <input type="text" v-model="query" @confirm="addHisTory" placeholder="请输入您想要的商品" />
      <button type="default" v-show="query.length" @tap="cancel">取消</button>
    </view>
    <!-- 底部 -->
    <view class="history-box">
      <view class="top">
        <text>历史记录</text>
        <icon @tap="clear" type="clear"></icon>
      </view>
      <view class="bottom">
        <view v-for="(item,index) in history" :key="index">
          {{item}}
        </view>
      </view>
    </view>
  </view>

</template>

<script>
  const KEY = 'history'
  export default {
    data() {
      return {
        // 双向绑定的内容
        query: '',
        // 搜索历史
        history: []
      }
    },
    onLoad() {
      // 缓存   getStorageSync  同步获取本地数据缓存
      const history = uni.getStorageSync(KEY)
      // 短路运算符
      this.history = history || []
    },
    methods: {
      // 取消事件
      cancel() {
        this.query = ""
      },
      // 清空历史
      clear() {
        this.history = []
        // 删除缓存的历史
        uni.clearStorageSync(KEY)
      },
      // 添加搜索历史
      addHisTory() {
        if (this.query === "") {
          return
        }
        this.history.push(this.query)
        // 去重
        const set = new Set(this.history)
        // 展开
        this.history = [...set]
        // 判断长度
        if (this.history.length > 5) {
          this.history.shift()
        }
        this.query = ''
        // 更新 缓存中的数据
        uni.setStorageSync(KEY, this.history)
      }
    }
  }
</script>

<style lang="less">
  .search-container {
    .search-box {
      background-color: #eeeeee;
      height: 120rpx;
      padding: 30rpx 20rpx 30rpx 10rpx;
      box-sizing: border-box;
      position: relative;
      display: flex;
      justify-content: space-between;

      // 图标
      icon {
        position: absolute;
        top: 48rpx;
        left: 30rpx;
      }

      // 输入框
      input {
        background-color: white;
        padding: 10rpx;
        padding-left: 70rpx;
        border-radius: 10rpx;
        margin-right: 20rpx;
        flex: 1;
        height: 60rpx;
      }

      // 按钮
      button {
        width: 160rpx;
        height: 78rpx;
        text-align: center;
        line-height: 78rpx;
        border-radius: 10rpx;
      }
    }

    .history-box {
      padding: 25rpx 30rpx 0 20rpx;

      .top {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .bottom {
        display: flex;
        flex-wrap: wrap;
        margin-top: 30rpx;

        view {
          padding: 20rpx;
          margin-right: 30rpx;
          margin-bottom: 30rpx;
          background-color: #dddddd;
        }
      }

    }
  }
</style>
